package com.ruoyi.api;

import com.ruoyi.common.AppController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.interceptor.annotation.IgnoreAuth;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.io.File;




/*通用数据接口*/
@RestController
@RequestMapping(value = "/api/data")
public class DataController extends AppController {


    /*单一图片文件上传*/
    @PostMapping("/uploadOneFile")
    @IgnoreAuth
    public Object uploadOneFile(MultipartFile file) {
        if (file == null) {
            return toResponsFail("缺少文件");
        }
        try {
            // 上传文件路径
            String photoPath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String photoSaveName = FileUploadUtils.upload(photoPath, file);
            /*生成缩略图*/
            String scaleImg = photoSaveName;
            if (StringUtils.isNotEmpty(photoSaveName) && photoSaveName.indexOf(".") != -1) {
                scaleImg = photoSaveName.substring(0, photoSaveName.lastIndexOf(".")) + "_2_" + photoSaveName.substring(photoSaveName.lastIndexOf("."));
                scaleImg = scaleImg.substring(15);
            }
            File fromFile = new File(photoPath + photoSaveName.substring(15));
            File toPic = new File(photoPath + scaleImg);
            Thumbnails.of(fromFile).scale(1f).outputQuality(0.5f).toFile(toPic);
            String resUrl = Constants.RESOURCE_PREFIX + "/upload/" + scaleImg;
            return writeResultRep(resUrl);
        } catch (Exception e) {
            return toResponsFail(e.getMessage());
        }
    }

    /*多文件图片上传*/
    @PostMapping("/uploadManyFiles")
    @IgnoreAuth
    public Object uploadManyFiles(MultipartFile[] files) {
        if (files.length == 0) {
            return toResponsFail("缺少文件");
        }
        StringBuffer manyUrls = new StringBuffer();
        try {
            // 上传文件路径
            String photoPath = RuoYiConfig.getUploadPath();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String photoSaveName = FileUploadUtils.upload(photoPath, file);
                String scaleImg = photoSaveName;
                if (StringUtils.isNotEmpty(photoSaveName) && photoSaveName.indexOf(".") != -1) {
                    scaleImg = photoSaveName.substring(0, photoSaveName.lastIndexOf(".")) + "_2_" + photoSaveName.substring(photoSaveName.lastIndexOf("."));
                    scaleImg = scaleImg.substring(15);
                }
                File fromFile = new File(photoPath + photoSaveName.substring(15));
                File toPic = new File(photoPath + scaleImg);
                Thumbnails.of(fromFile).scale(1f).outputQuality(0.5f).toFile(toPic);
                String resUrl = Constants.RESOURCE_PREFIX + "/upload/" + scaleImg;
                if (StringUtils.isEmpty(manyUrls.toString())) {
                    manyUrls.append(photoSaveName);
                } else {
                    manyUrls.append("|" + resUrl);
                }
            }
            return writeResultRep(manyUrls.toString());
        } catch (Exception e) {
            return toResponsFail(e.getMessage());
        }
    }


    /*视频文件上传*/
    @PostMapping("/uploadOneVideo")
    @IgnoreAuth
    public Object uploadOneVideo(MultipartFile file) {
        if (file == null) {
            return toResponsFail("缺少文件");
        }
        try {
            System.out.println("上传视频中..............");
            // 上传文件路径
            String videoPath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String videoSaveName = FileUploadUtils.upload(videoPath, file);
            System.out.println("成功上传视频返回的链接地址" + videoSaveName);
            return writeResultRep(videoSaveName);
        } catch (Exception e) {
            return toResponsFail(e.getMessage());
        }
    }


    /**
     * 传视频File对象，返回压缩后File对象信息
     *
     * @param toFile
     */
   /* @PostMapping("/compressVideo")
    @IgnoreAuth
    public Object compressVideo(MultipartFile toFile) {
        if (toFile == null) {
            return toResponsFail("缺少文件");
        }
        File source = null;
        File target = null;
        String filePrex = System.currentTimeMillis() + "";
        try {
            InputStream ins = toFile.getInputStream();
            source = new File(toFile.getOriginalFilename());
            inputStreamToFile(ins, source);
            ins.close();

            String newPath = RuoYiConfig.getUploadPath() + "/video/" + filePrex + toFile.getOriginalFilename();
            System.out.println(newPath);
            target = new File(newPath);

            MultimediaObject object = new MultimediaObject(source);
            AudioInfo audioInfo = object.getInfo().getAudio();
            // 根据视频大小来判断是否需要进行压缩,
            int maxSize = 5;
            double mb = Math.ceil(source.length() / 1048576);
            int second = (int) object.getInfo().getDuration() / 1000;
            BigDecimal bd = new BigDecimal(String.format("%.4f", mb / second));
            System.out.println("开始压缩视频了--> 视频每秒平均 " + bd + " MB ");
            // 视频 > 5MB, 或者每秒 > 0.5 MB 才做压缩， 不需要的话可以把判断去掉
            boolean temp = mb > maxSize || bd.compareTo(new BigDecimal(0.5)) > 0;
//            if(temp){
            long time = System.currentTimeMillis();
            //TODO 视频属性设置
            int maxBitRate = 128000;
            int maxSamplingRate = 44100;
            int bitRate = 800000;
            int maxFrameRate = 20;
            int maxWidth = 1280;

            AudioAttributes audio = new AudioAttributes();
            // 设置通用编码格式10                   audio.setCodec("aac");
            // 设置最大值：比特率越高，清晰度/音质越好
            // 设置音频比特率,单位:b (比特率越高，清晰度/音质越好，当然文件也就越大 128000 = 182kb)
            if (audioInfo.getBitRate() > maxBitRate) {
                audio.setBitRate(new Integer(maxBitRate));
            }

            // 设置重新编码的音频流中使用的声道数（1 =单声道，2 = 双声道（立体声））。如果未设置任何声道值，则编码器将选择默认值 0。
            audio.setChannels(audioInfo.getChannels());
            // 采样率越高声音的还原度越好，文件越大
            // 设置音频采样率，单位：赫兹 hz
            // 设置编码时候的音量值，未设置为0,如果256，则音量值不会改变
            // audio.setVolume(256);
            if (audioInfo.getSamplingRate() > maxSamplingRate) {
                audio.setSamplingRate(maxSamplingRate);
            }

            //TODO 视频编码属性配置
            ws.schild.jave.info.VideoInfo videoInfo = object.getInfo().getVideo();
            VideoAttributes video = new VideoAttributes();
            video.setCodec("h264");
            //设置音频比特率,单位:b (比特率越高，清晰度/音质越好，当然文件也就越大 800000 = 800kb)
            if (videoInfo.getBitRate() > bitRate) {
                video.setBitRate(bitRate);
            }

            // 视频帧率：15 f / s  帧率越低，效果越差
            // 设置视频帧率（帧率越低，视频会出现断层，越高让人感觉越连续），视频帧率（Frame rate）是用于测量显示帧数的量度。所谓的测量单位为每秒显示帧数(Frames per Second，简：FPS）或“赫兹”（Hz）。
            if (videoInfo.getFrameRate() > maxFrameRate) {
                video.setFrameRate(maxFrameRate);
            }

            // 限制视频宽高
            int width = videoInfo.getSize().getWidth();
            int height = videoInfo.getSize().getHeight();
            if (width > maxWidth) {
                float rat = (float) width / maxWidth;
                video.setSize(new VideoSize(maxWidth, (int) (height / rat)));
            }

            EncodingAttributes attr = new EncodingAttributes();
//                attr.setFormat("mp4");
            attr.setAudioAttributes(audio);
            attr.setVideoAttributes(video);

            // 速度最快的压缩方式， 压缩速度 从快到慢： ultrafast, superfast, veryfast, faster, fast, medium,  slow, slower, veryslow and placebo.
//                attr.setPreset(PresetUtil.VERYFAST);
//                attr.setCrf(27);
//                // 设置线程数
//                attr.setEncodingThreads(Runtime.getRuntime().availableProcessors()/2);

            Encoder encoder = new Encoder();
            encoder.encode(new MultimediaObject(source), target, attr);
            System.out.println("压缩总耗时：" + (System.currentTimeMillis() - time) / 1000);
            return Constants.RESOURCE_PREFIX + "/upload/video/" + filePrex + toFile.getOriginalFilename();
//            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (target.length() > 0) {
                source.delete();
            }
        }
        return source;
    }

    public void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    /*===========================================断点续传===================================================*/
    /**
     * 获取已上传的文件大小
     *
     * @param
     * @param
     */
    @RequestMapping("getChunkedFileSize")
    @IgnoreAuth
    public Object getChunkedFileSize(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return toResponsFail("缺少文件名称");
        }
        //存储文件的路径，根据自己实际确定
        String currentFilePath = RuoYiConfig.getUploadPath() + "/video/" + fileName;
        System.out.println("文件地址:" + currentFilePath);

        try {
            File source = new File(currentFilePath);
            if (source.exists()) {
                return source.length();
            } else {
                return 0L;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 断点文件上传
     */
    @RequestMapping("breakPointUploadFileDo")
    @IgnoreAuth
    public Object breakPointUploadFileDo(MultipartFile file, long startLength, String fileName) {

        if (file.getSize() <= 0) {
            return toResponsFail("请选择上传的文件！");
        }
        System.out.println("从" + startLength + "开始续传");

        String writeFileName = RuoYiConfig.getUploadPath() + "/video/" + fileName;
        File source = new File(writeFileName);
        RandomAccessFile writeFile=null;
        InputStream iStream=null;
        // 存在文件
        try {
            if (source.exists()) {

                writeFile = new RandomAccessFile(source, "rw");
            } else {

                // 不存在文件，根据文件标识创建文件
                writeFile = new RandomAccessFile(writeFileName, "rw");
            }
            writeFile.seek(startLength);
            byte[] arr = new byte[1024];
            int len = 0;
             iStream = file.getInputStream();
            while ((len = iStream.read(arr)) != -1) {
                writeFile.write(arr, 0, len);
            }

        } catch (final Exception e) {
            throw new RuntimeException("断点上传文件异常", e);
        } finally {
            try {
                iStream.close();
                writeFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return writeResultRep(writeFileName);
    }

    /*==================================================分片=========================================================*/

    /**
     * 上传分片文件
     * @param guid
     * @param chunk
     * @param file
     */
    @RequestMapping("/uploadBurstFile")
    @IgnoreAuth
    public Object uploadBurstFile(MultipartFile file,String guid,Integer chunk){
        if(file==null || StringUtils.isEmpty(guid) || StringUtils.isNull(chunk)){
            return toResponsFail("缺少参数传递");
        }
        try {
            String filePath= RuoYiConfig.getUploadPath() + "/video/";
            // 临时目录用来存放所有分片文件
            String tempFileDir = filePath + guid;
            File parentFileDir = new File(tempFileDir);
            if (!parentFileDir.exists()) {
                parentFileDir.mkdirs();
            }
            // 分片处理时，前台会多次调用上传接口，每次都会上传文件的一部分到后台
            File tempPartFile = new File(parentFileDir, guid + "_" + chunk + ".part");
            FileUtils.copyInputStreamToFile(file.getInputStream(), tempPartFile);
            return writeResultRep();
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("分片上传失败");
        }
    }

    /**
     * 合并分片文件
     * @param guid
     * @param fileName
     * @throws Exception
     */
    @RequestMapping( "/mergeBurstFile")
    @IgnoreAuth
    public Object mergeBurstFile(String guid,String fileName){
        // 得到 destTempFile 就是最终的文件
        try {
            String filePath= RuoYiConfig.getUploadPath() + "/video/";
            String nowDate= DateUtils.dateTimeNow();
            File parentFileDir = new File(filePath  +guid );
            if(parentFileDir.isDirectory()){
                File destTempFile = new File(filePath+nowDate, fileName);
                //先得到文件的上级目录，并创建上级目录，在创建文件,
                if (!destTempFile.getParentFile().exists()){
                    destTempFile.getParentFile().mkdir();
                }
                if(!destTempFile.exists()){
                    try {
                        //创建文件
                        destTempFile.createNewFile(); //上级目录没有创建，这里会报错
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(parentFileDir.listFiles().length);
                for (int i = 0; i < parentFileDir.listFiles().length-1; i++) {
                    File partFile = new File(parentFileDir, guid + "_" + i + ".part");
                    FileOutputStream destTempfos = new FileOutputStream(destTempFile, true);
                    //遍历"所有分片文件"到"最终文件"中
                    FileUtils.copyFile(partFile, destTempfos);
                    destTempfos.close();
                }
                // 删除临时目录中的分片文件
                FileUtils.deleteDirectory(parentFileDir);
                return writeResultRep(Constants.RESOURCE_PREFIX + "/upload/video/"+nowDate + "/" +fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail(e.getMessage());
        }
        return null;
    }

}
